package com.myleo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.sql.DataSource;
import java.io.*;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Main {

    public static void main(String[] args) {
        jdbcQueryTest();
    }

    private static void classTest() {
//        List<Student> listStudents = new ArrayList<Student>();
//        Student s1 = new Student("Leo", 35);
//
//
//        Student s2 = new Student("Peter", 15);
//
//        listStudents.add(s1);
//        listStudents.add(s2);
//        int nCount = listStudents.size();
//        for (Student s : listStudents) {
//            System.out.println(s.getName() + ", " + s.getAge() + "岁, 编号" + s.getId());
//        }
    }

    private static void hello() {
        String strName = "Leo";
        System.out.print(strName);
        strName = "Wang Dou Dou";
        System.out.println(strName);
    }

    /**
     * 基本数据类型实验
     */
    private static void dataTypeTest() {
        int iA = 1;
        double dA = 1.1;
        float fA = 1.1f;
        boolean blA = true;
        long lA = 11111111111111111L;
        char cA = 'a';
        String[] arrB = {"a", "b", "c"};
        int[] arrA = {1, 2, 3, 4};

        //hashMap
        HashMap<String, Integer> map = new HashMap<>();
        map.put("zou", 32);
        map.put("lee", 32);
        map.put("peter", 32);
        System.out.println(map.size());
        //通过key集合读取所有制
        for (String s : map.keySet()) {
            System.out.println(map.get(s));
        }
        //迭代器读取所有值
        for (int i : map.values()) {
            System.out.println(i);
        }
    }

    private static void dateTest() {
        Date dt = new Date(2019 - 1900, 8 - 1, 12);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        System.out.println(format.format(dt));

        Calendar calendar = new GregorianCalendar();
        //Date转Calendar
        calendar.setTime(dt);
        //Calendar转Date
        calendar.getTime();
        //加一年
        calendar.add(Calendar.YEAR, 1);
        //加一个月
        calendar.add(Calendar.MONTH, 1);
        //加一天
        calendar.add(Calendar.DATE, 1);
        //加一小时
        calendar.add(Calendar.HOUR, 1);
        //加一分钟
        calendar.add(Calendar.MINUTE, 1);
        //加一秒
        calendar.add(Calendar.SECOND, 1);
        //加一毫秒
        calendar.add(Calendar.MILLISECOND, 1);
        //Calendar 转 string
        System.out.println(calendar.get(Calendar.YEAR));
    }

    private static void dateTest2() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date dt2 = null;
        try {
            //string转Date
            dt2 = format.parse("2011-04-06 04:22:31");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //Date转string
        String strDate = format.format(dt2);
    }

    private static void dateTest3() {
        Calendar cal = new GregorianCalendar();
        Date dtNow = new Date();
        cal.setTime(dtNow);
        cal.add(Calendar.HOUR, 8);
        Date dtNew = cal.getTime();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        System.out.println(format.format(dtNow));
        System.out.println(format.format(dtNew));
    }

    /**
     * 读取文件二进制数组，二进制转文本
     */
    private static void ioReadTest() {
        String strCurrentDir = System.getProperty("user.dir");
        String filePath = strCurrentDir + "\\src\\com\\myleo\\" + "test.json";
        File file = new File(filePath);
        InputStream ins = null;
        try {
            ins = new FileInputStream(file);
            int nFileSize = ins.available();
            List<Byte> bits = new ArrayList<>();
            byte[] bitRead = new byte[10];
            int nReadCount = -1;
            do {
                nReadCount = ins.read(bitRead);
                for (int i = 0; i < nReadCount; i++) {
                    bits.add(bitRead[i]);
                }
            } while (nReadCount > -1);

            byte[] newBits = new byte[bits.size()];
            Iterator<Byte> iterator = bits.iterator();
            int nA = 0;
            while (iterator.hasNext()) {
                newBits[nA++] = iterator.next();
            }
            String strContent = new String(newBits, "GBK");
            System.out.println(strContent);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取文本文件或者Json文件
     */
    private static void ioReadContent() {
        //获取程序安装路径
        String strCurrentDir = System.getProperty("user.dir");
        String strFilePath = strCurrentDir + "\\src\\com\\myleo\\" + "test.json";
        //没啥用，只是代表一个文件或文件夹，可以用来判断文件是否存在
        File file = new File(strFilePath);
        //File的作用就这点
        if (file.isFile() && file.exists()) {
            try {
                //FileReader reader = new FileReader(file);
                //这东西只能都字节数组
                FileInputStream stream = new FileInputStream(strFilePath);
                //这东西可以一个个字符数组读出来。
                InputStreamReader reader = new InputStreamReader(stream, "GBK");
                //据说FileReader、InputStreamReader读取很低效，建议用这玩意包装他们来读就很快。
                BufferedReader bufferedReader = new BufferedReader(reader);

                String strLine = null;
                StringBuilder sb = new StringBuilder();
                do {
                    strLine = bufferedReader.readLine();
                    if (strLine != null) {
                        sb.append(strLine);
                        sb.append("\r\n");
                    }
                } while (strLine != null);
                System.out.println(sb.toString());

                bufferedReader.close();
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void stringTest() {
        String strTest = "asdf123";
        //字符串切割
        String[] aa = "1,2,3,4,5&a,b,c,d".split("[,&]");
        //字符串查找
        System.out.println(strTest.indexOf("1"));
        //获取指定位置字符串
        System.out.println(strTest.charAt(3));
        //截取指定字符串
        System.out.println(strTest.substring(3, 2));
        //去前后空格
        System.out.println(strTest.trim());
        //字符串替换
        System.out.println(strTest.replace("1", "一"));
        //判断字符串是否以指定内容开始或结束
        System.out.println(strTest.startsWith("cc"));
        System.out.println(strTest.endsWith("cc"));
        //判断字符串是否相对
        System.out.println("123".equals("ada"));
        //大小写转换
        System.out.println("ada".toLowerCase());
        System.out.println("ada".toUpperCase());
        //字符串数组拼接字符串
        StringBuilder sb = new StringBuilder();
        for (String a : aa) {
            sb.append(a);
        }
        String str = sb.toString();
    }

    private static void patternTest() {
        String content = "I am noob from runoob.com.";

        String pattern = ".*runoob.*";

        boolean isMatch = Pattern.matches(pattern, content);

        System.out.println("字符串中是否包含了 'runoob' 子字符串? " + isMatch);

        pattern = "(\\D*)(\\d+)(.*)";
        Matcher matcher = Pattern.compile(pattern).matcher(content);
        matcher.group(0);
        matcher.group(1);
        matcher.group(2);
        matcher.replaceAll("x");
    }

    /**
     * 反序列化，用数组的方式读取结构
     */
    private static void jsonTest1() {
        try {
            String strCurrentDir = System.getProperty("user.dir");
            String filePath = strCurrentDir + "\\src\\com\\myleo\\" + "test.json";
            File file = new File(filePath);
            if (!file.exists() || !file.isFile()) {
                return;
            }

            InputStream in = new FileInputStream(file);
            InputStreamReader reader = new InputStreamReader(in, "GBK");
            BufferedReader breader = new BufferedReader(reader);
            StringBuilder sb = new StringBuilder();
            while (true) {
                String strLine = breader.readLine();
                if (strLine == null) {
                    break;
                }
                sb.append(strLine);
                sb.append("\r\n");
            }

            String jsonStr = sb.toString();

            ObjectMapper objectMapper = new ObjectMapper();

            JsonNode jsonNode = objectMapper.readTree(jsonStr);
            if (jsonNode.isObject()) {
                String strName = jsonNode.get("data").get(1).get("name").textValue();
                int nCount = jsonNode.get("data").size();
                jsonNode.fields().forEachRemaining(entry -> {
                    String fieldName = entry.getKey();
                    JsonNode nestedNode = entry.getValue();
                    // .. do something with nested node
                });
            } else if (jsonNode.isArray()) {
                jsonNode.elements().forEachRemaining(subElem -> {
                    // ... do something with sub element
                });
            } else {
                String value = jsonNode.asText();
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    /**
     * 反序列化，反序列化为对象。
     */
    private static void jsonTest2() {
        try {
            String strCurrentDir = System.getProperty("user.dir");
            String filePath = strCurrentDir + "\\config\\test.json";
            File file = new File(filePath);
            if (!file.exists() || !file.isFile()) {
                return;
            }

            InputStream in = new FileInputStream(file);
            InputStreamReader reader = new InputStreamReader(in, "GBK");
            BufferedReader breader = new BufferedReader(reader);
            StringBuilder sb = new StringBuilder();
            while (true) {
                String strLine = breader.readLine();
                if (strLine == null) {
                    break;
                }
                sb.append(strLine);
                sb.append("\r\n");
            }

            String jsonStr = sb.toString();

            ObjectMapper map = new ObjectMapper();
            //读取整个json
            JsonNode node = map.readTree(jsonStr);
            //因为是http返回格式，data属性的内容才是真的对象。
            String jsonStrData = node.get("data").toString();
            Person[] obj = map.readValue(jsonStrData, Person[].class);
            System.out.println(obj.length);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    //序列化
    private static void jsonTest3() {
        Person p1 = new Person("leo", 35, 1);
        Person p2 = new Person("peter", 14, 1);
        Person p3 = new Person("lily", 18, 0);

        ObjectMapper map = new ObjectMapper();
        try {
            String strJson = map.writeValueAsString(p1);
            System.out.println(strJson);

            Person[] ps = {p1, p2, p3};
            strJson = map.writeValueAsString(ps);
            System.out.println(strJson);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

    }

    private static void jdbcQueryTest(){
        String strUrl = "jdbc:mysql://127.0.0.1:3306/test?useSSL=true";
        String strUser = "root";
        String strPwd = "P@ssw0rd";

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //SQLConnection
            Connection conn = DriverManager.getConnection(strUrl, strUser, strPwd);
            //SQLCommander
            Statement statement = conn.createStatement();
            //DataTable
            boolean blSuccess = statement.execute("select * from jz_news limit 10;");
            if(blSuccess){
                ResultSet rs = statement.getResultSet();
                //ResultSetMetaData meta = rs.getMetaData();

                while (rs.next()){
                    System.out.println(rs.getString("news_title"));
                }
                System.out.println("end");
            }
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    private static void jdbcUpdateTest(){
        String strUrl = "jdbc:mysql://127.0.0.1:3306/test?useSSL=true";
        String strUser = "root";
        String strPwd = "P@ssw0rd";
        try{
            Connection conn = DriverManager.getConnection(strUrl, strUser, strPwd);
            PreparedStatement statement = conn.prepareStatement("update person set age = ? where name = 'leo'");
            statement.setInt(1,18);
            int nRow = statement.executeUpdate();
            System.out.println("exec row: " + nRow);
        }
        catch (SQLException e){
            e.printStackTrace();
        }
    }

    private void jdbcInserTest(){
        String strUrl = "jdbc:mysql://127.0.0.1:3306/test?useSSL=true";
        String strUser = "root";
        String strPwd = "P@ssw0rd";
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection conn = DriverManager.getConnection(strUrl, strUser, strPwd);
            PreparedStatement statement = conn.prepareStatement("insert into person(id,name,age)  values(?,?,?)");
            statement.setString(1,UUID.randomUUID().toString());
            statement.setString(2,"leo");
            statement.setInt(3,36);
            int nRow = statement.executeUpdate();
            System.out.println("exec row: " + nRow);
        }catch (SQLException | ClassNotFoundException e){
            e.printStackTrace();
        }
    }

    private static void mybatisTest() {
        // mybatis配置文件
        String resource = "SqlMapConfig.xml";
        // 得到配置文件流
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);


            // 创建会话工厂，传入mybatis的配置文件信息
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder()
                    .build(inputStream);

            // 通过工厂得到SqlSession
            SqlSession sqlSession = sqlSessionFactory.openSession();

            // 通过SqlSession操作数据库
            // 第一个参数：映射文件中statement的id，等于=namespace+"."+statement的id
            // 第二个参数：指定和映射文件中所匹配的parameterType类型的参数
            // sqlSession.selectOne结果 是与映射文件中所匹配的resultType类型的对象
            // selectOne查询出一条记录
            //User user = sqlSession.selectOne("test.findUserById", 1);
            List<Test> list = sqlSession.selectList("haha.findAllTest");

            System.out.println(list.size());

            // 释放资源
            sqlSession.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


